import { type NextRequest, NextResponse } from 'next/server';
import { NotesHandler } from './handlers/notesHandler';
import { UsersHandler } from './handlers/usersHandler';
import { PostsHandler } from './handlers/postsHandler';
import { WeatherHandler } from './handlers/weatherHandler';

export class ProxyBackendUtils {
    private proxyUrl = '/api/backend';
    private notesHandler = new NotesHandler();
    private usersHandler = new UsersHandler();
    private postsHandler = new PostsHandler();
    private weatherHandler = new WeatherHandler();

    request = async (request: NextRequest) => {
        // 若未配置外部后端 URL，直接在当前类中处理请求（不再转发到内部路由）
        if (!process.env.APP_BACKEND_URL) {
            return this.handleRequestDirectly(request); // 替换原 forwardToInternalAPI 调用真实的
        }
        // 外部后端逻辑保持不变...
        const url = this.buildExternalBackendUrl(request);
        const requestOptions = await this.buildRequestOptions(request);
        console.log('ProxyBackendUtils request:', url, requestOptions);
        const result = await fetch(url, requestOptions);
        const parsedResult = (await result.json()) as unknown;

        return NextResponse.json(parsedResult, result);
    };

    // 新增：直接处理请求（替代内部路由转发）
    private handleRequestDirectly = async (request: NextRequest) => {
        // 提取请求路径（原 relativeUrl，例如 "/users/123" → "users/123"）
        const [, relativeUrl] = request.nextUrl.href.split(this.proxyUrl);
        const cleanRelativeUrl = relativeUrl.startsWith('/') ? relativeUrl.substring(1) : relativeUrl;

        // 根据路径直接处理不同端点（无需创建 /api 子文件夹）
        if (cleanRelativeUrl.startsWith('notes')) {
            return this.notesHandler.handle(request);
        }
        if (cleanRelativeUrl.startsWith('users')) {
            return this.usersHandler.handle(request);
        }
        if (cleanRelativeUrl.startsWith('posts')) {
            return this.postsHandler.handle(request);
        }
        if (cleanRelativeUrl.startsWith('weather')) {
            return this.weatherHandler.handle(request);
        }

        return NextResponse.json(
            { error: `Endpoint ${cleanRelativeUrl} not found` },
            { status: 404 }
        );
    };

    private buildExternalBackendUrl = (request: NextRequest): string => {
        const [, relativeUrl] = request.nextUrl.href.split(this.proxyUrl);
        const url = `${process.env.APP_BACKEND_URL}${relativeUrl}`;
        return url;
    };

    private buildRequestOptions = async (request: NextRequest): Promise<RequestInit> => {
        const { method, headers } = request;
        const body = method.toUpperCase() === 'POST' ? await request.text() : undefined;

        return { method, body, headers };
    };
}

export const proxyBackendUtils = new ProxyBackendUtils();
